import axios from 'axios'
import { Message, Notification  } from 'element-ui';
import store from '@/store'

//自定义实例
const request = axios.create()
request.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
request.defaults.baseURL = process.env.BASE_API
request.defaults.timeout = '30000'

//请求拦截
request.interceptors.request.use(
  config => { //发送请求之前的操作\
    let token = localStorage.getItem('Authorization');
    if(token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config;
  },
  error => { //对错误请求的操作
    console.log(error)
    return Promise.reject(error);
  }
);

//响应拦截
request.interceptors.response.use(
  response => { //对响应数据进行的操作
    console.log(response)
    if(response.data.code === 202) { //请求失败
      Message.error(response.data.message)
    }
    return response;
  },
  error => { //对错误响应的操作
    console.log(error.response)
    let code  = error.response.data.code;
    let message = error.response.data.message;
    if(code === 302) { //未授权访问
      Message.error(message);
      store.dispatch('userLogout');
    }
    if(code === 401) { //授权失败
      Message.error(message);
    }
    if(code === 403) { //无权限禁止访问
      Notification.warning({
        title: '提示',
        message: message
      })
    }
    if(code === 704) { //验证码失败
      Message.error(message);
    }
    return Promise.reject(error.response);
  }
);

export default request
